package com.example.piece.ui.adapter

import android.graphics.Color
import android.os.Build
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatEditText
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.chad.library.adapter.base.BaseNodeAdapter
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.provider.BaseNodeProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.base.aop.login.LoginCallback
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.navigationTo
import com.example.base.ext.setCornersPlaceHolderImageUrl
import com.example.base.ext.toast
import com.example.base.popup.util.KeyboardUtils
import com.example.base.tools.ConfigTool
import com.example.base.ui.activity.BaseActivity
import com.example.base.vm.onError
import com.example.piece.App
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ItemHomeRecommendationVideoBinding
import com.example.piece.databinding.ItemPlLeftBinding
import com.example.piece.databinding.ItemPlLeftSecondBinding
import com.example.piece.entity.JokesCommentEntity
import com.example.piece.entity.JokesItemCommentListEntity
import com.example.piece.tools.SIMCardInfo
import com.example.piece.vm.JokesViewModel
import com.example.piece.vm.UserViewModel
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.FullScreenDialog
import com.kongzue.dialogx.interfaces.DialogLifecycleCallback
import com.kongzue.dialogx.interfaces.OnBindView


class PingLunNodeAdapter//需要占满一行
//普通的item provider
//    addNodeProvider(RootNodeProvider())
/* //添加脚布局
 addFooterNodeProvider()*/ : BaseNodeAdapter , LoadMoreModule {
    private val jokesViewModel: JokesViewModel
    private val userViewModel: UserViewModel

    constructor(
        userViewModel: UserViewModel,
        jokesViewModel: JokesViewModel,
        fragment: BaseActivity<ViewDataBinding>,
    ) : super() {
        this.jokesViewModel = jokesViewModel
        this.userViewModel = userViewModel

        addFullSpanNodeProvider(RootNodeProvider(userViewModel, jokesViewModel, fragment))
        addNodeProvider(SecondNodeProvider(userViewModel,jokesViewModel, fragment))
    }

    override fun getItemType(data: List<BaseNode>, position: Int): Int {
        val node = data[position]
        if (node is JokesItemCommentListEntity) {
            return 1
        } else if (node is JokesCommentEntity) {
            return 0
        }
        return -1
    }


    class RootNodeProvider : BaseNodeProvider {
        private val jokesViewModel: JokesViewModel
        private val fragment: BaseActivity<ViewDataBinding>
        private val userViewModel: UserViewModel


        constructor(
            userViewModel: UserViewModel,
            jokesViewModel: JokesViewModel,
            fragment: BaseActivity<ViewDataBinding>,
        ) : super() {
            this.userViewModel = userViewModel

            this.jokesViewModel = jokesViewModel
            this.fragment = fragment
        }

        override val itemViewType: Int = 0
        override val layoutId: Int = R.layout.item_pl_left

        /**
         * 当 ViewHolder 创建完毕以后，会执行此回掉
         * 可以在这里做任何你想做的事情
         */
        override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
            // 绑定View
            DataBindingUtil.bind<ItemPlLeftBinding>(viewHolder.itemView)
        }

        override fun convert(helper: BaseViewHolder, item: BaseNode) {
            val binding = DataBindingUtil.getBinding<ItemPlLeftBinding>(helper.itemView)
            val jokesCommentEntity = item as JokesCommentEntity

            binding?.imgHead?.setCornersPlaceHolderImageUrl(
                jokesCommentEntity.commentUser.userAvatar,
                90,
                R.drawable.header_img
            )
            binding?.tvName?.text = jokesCommentEntity.commentUser.nickname
            binding?.tvPl?.text = jokesCommentEntity.content
            binding?.tvTime?.text = jokesCommentEntity.timeStr
            binding?.imgLike?.isSelected = jokesCommentEntity.isLike
            binding?.tvLikeNum?.text = jokesCommentEntity.likeNum

            binding?.tvDelete?.visibility =
                if (jokesCommentEntity.commentUser.userId ==App.userLoginCodeEntity.user.userId) View.VISIBLE else View.INVISIBLE

            binding?.imgLike?.setOnClickListener {

                jokesViewModel.jokesCommentLike(fragment,
                    jokesCommentEntity.commentId,
                    (!jokesCommentEntity.isLike).toString()) {
                    if (it.code == 200) {
                        jokesCommentEntity.isLike = !jokesCommentEntity.isLike

                        if (jokesCommentEntity.isLike) {
                            jokesCommentEntity.likeNum =
                                (jokesCommentEntity.likeNum.toLong() + 1).toString()

                        } else {
                            jokesCommentEntity.likeNum =
                                (jokesCommentEntity.likeNum.toLong() - 1).toString()

                        }
                        binding?.imgLike?.isSelected = jokesCommentEntity.isLike

                        binding?.tvLikeNum?.text = jokesCommentEntity.likeNum

                    }

                } onError {

                }
            }

            binding?.tvHuifu?.setOnClickListener {
                huifu(item)
            }
            binding?.tvDelete?.setOnClickListener {

                jokesViewModel.jokesCommentDelete(fragment,item.commentId){
                    if (it.code == 200) {

                        val adapter = getAdapter()
                        //adapter?.notifyDataSetChanged()
                        adapter?.remove(item)
                    }
                }onError {

                }

            }
            binding?.executePendingBindings()

        }
        @LoginCallback
        private fun huifu(item: JokesCommentEntity) {
          /*  if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
                gotoLogin()
            } else {*/
                BottomDialog.show(object :
                    OnBindView<BottomDialog>(R.layout.dialog_pinglun_write) {
                    override fun onBind(dialog: BottomDialog?, v: View?) {
                        val etPL = v?.findViewById<AppCompatEditText>(R.id.et_pl)
                        etPL?.postDelayed({ KeyboardUtils.open(etPL) }, 100)
                        etPL?.hint = "回复：" + item.commentUser.nickname
                        val imgSend = v?.findViewById<ImageView>(R.id.img_send)
                        etPL?.addTextChangedListener(object : TextWatcher {
                            override fun beforeTextChanged(
                                s: CharSequence?,
                                start: Int,
                                count: Int,
                                after: Int,
                            ) {
                            }

                            override fun onTextChanged(
                                s: CharSequence?,
                                start: Int,
                                before: Int,
                                count: Int,
                            ) {
                                imgSend?.isSelected = !s.isNullOrEmpty()
                            }

                            override fun afterTextChanged(s: Editable?) {

                            }
                        })

                        imgSend?.setOnClickListener {
                            if (!etPL?.text.toString().isNullOrEmpty()) {//提交评论
                                jokesViewModel.jokesCommentItem(fragment,
                                    item.commentId,
                                    etPL?.text.toString(),
                                    false) {
                                    if (it.code == 200) {
                                        val data = it.data

                                        val adapter = getAdapter()
                                        adapter?.nodeAddData(item, data)
                                        dialog?.dismiss()
                                    }

                                } onError {

                                }
                            }

                        }


                    }

                }).isAllowInterceptTouch = false
            //}
        }

        override fun onClick(helper: BaseViewHolder, view: View, data: BaseNode, position: Int) {
            getAdapter()?.expandOrCollapse(position)
        }

        private fun gotoLogin() {
            val onBindView =
                object :
                    OnBindView<FullScreenDialog>(R.layout.layout_full_login, true) {
                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
                    override fun onBind(dialog: FullScreenDialog?, v: View?) {
                        val tvPhone = v?.findViewById<EditText>(R.id.edit_userName)
                        v?.findViewById<TextView>(R.id.tv_getCode)//获取验证码
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userLoginGetCode(
                                        fragment,
                                        tvPhone?.text.toString()
                                    ) {
                                        fragment.toast(it.msg)
                                    } onError {
                                        fragment.toast(it)

                                    }
                                } else {
                                    fragment.toast("请输入手机号码！")
                                }

                            }
                        v?.findViewById<TextView>(R.id.tv_loginByOwenPhone)
                            ?.setOnClickListener {
                                getOwnPhone(tvPhone)
                            }

                        val etPsd = v?.findViewById<TextView>(R.id.edit_password)

                        v?.findViewById<ImageView>(R.id.img_qq)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userPswReset(
                                        fragment,
                                        etPsd?.text.toString(), "111sam111",
                                        tvPhone?.text.toString()
                                    ) {
                                        fragment.toast(it.msg)
                                    } onError {
                                        fragment.toast(it)

                                    }
                                } else {
                                    fragment.toast("请输入手机号码！")
                                }
                            }
                        v?.findViewById<TextView>(R.id.btn_submit)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    if (!etPsd?.text.isNullOrEmpty()) {
                                        userViewModel.userLoginCode(
                                            fragment,
                                            etPsd?.text.toString(),
                                            tvPhone?.text.toString()
                                        ) {
                                            if (it.code === 200) {
                                                App.USER_TOKEN = it.data.token
                                                //存本地token
                                                ConfigTool.putString(Key.DataKey.TOKEN,
                                                    it.data.token)
                                                //登录成功
                                                EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))
                                                dialog?.dismiss()
                                            }
                                        } onError {
                                            fragment.toast(it)

                                        }
                                    } else {
                                        fragment.toast("请输入验证码！")

                                    }

                                } else {
                                    fragment.toast("请输入手机号码！")
                                }
                            }


                        val spannableStringBuilder = SpannableStringBuilder()
                        //设置文字
                        spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
                        //设置文字点击事件（用户协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "用户协议",

                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                        //设置文字点击事件（隐私协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "隐私协议",
                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        //设置颜色
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )


                        val tvXieYi = v?.findViewById<TextView>(R.id.tv_xieyi)
                        tvXieYi?.movementMethod = LinkMovementMethod.getInstance()
                        tvXieYi?.text = spannableStringBuilder

                    }

                }
            FullScreenDialog.show(onBindView).dialogLifecycleCallback = object :
                DialogLifecycleCallback<FullScreenDialog>() {
                override fun onDismiss(dialog: FullScreenDialog?) {
                    super.onDismiss(dialog)

                }

                override fun onShow(dialog: FullScreenDialog?) {
                    super.onShow(dialog)
                }

            }
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        fun getOwnPhone(phone: TextView?) {
            val phoneNumbers =
                fragment?.let { SIMCardInfo(it).phoneNumberS }
            if (phoneNumbers?.isNotEmpty() == true) {
                for (it in phoneNumbers) {

                }
                phone?.text = phoneNumbers[0]

            } else {
                fragment.toast("暂未获取到手机号")
            }


        }
    }


    class SecondNodeProvider :  BaseNodeProvider {
        private val jokesViewModel: JokesViewModel
        private val fragment: BaseActivity<ViewDataBinding>
        private val userViewModel: UserViewModel


        constructor(
            userViewModel: UserViewModel,
            jokesViewModel: JokesViewModel,
            fragment: BaseActivity<ViewDataBinding>,
        ) : super() {
            this.userViewModel = userViewModel

            this.jokesViewModel = jokesViewModel
            this.fragment = fragment
        }

        override val itemViewType: Int = 1
        override val layoutId: Int = R.layout.item_pl_left_second

        /**
         * 当 ViewHolder 创建完毕以后，会执行此回掉
         * 可以在这里做任何你想做的事情
         */
        override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
            // 绑定View
            DataBindingUtil.bind<ItemPlLeftSecondBinding>(viewHolder.itemView)
        }

        override fun convert(helper: BaseViewHolder, item: BaseNode) {
            val binding = DataBindingUtil.getBinding<ItemPlLeftSecondBinding>(helper.itemView)
            val jokesItemCommentListEntity = item as JokesItemCommentListEntity

            binding?.imgHead?.setCornersPlaceHolderImageUrl(
                jokesItemCommentListEntity.commentUser.userAvatar,
                90,
                R.drawable.header_img
            )
            binding?.tvName?.text = jokesItemCommentListEntity.commentUser.nickname
            binding?.tvPl?.text = jokesItemCommentListEntity.content
            binding?.tvTime?.text = jokesItemCommentListEntity.timeStr

            binding?.tvDelete?.visibility =
                if (App.userLoginCodeEntity.user.userId == jokesItemCommentListEntity.commentUser.userId)  View.VISIBLE else View.INVISIBLE


            binding?.tvHuifu?.setOnClickListener {
                huifu2(item)
            }
            binding?.tvDelete?.setOnClickListener {
                jokesViewModel.jokesCommentItemDelete(fragment,item.commentItemId){
                    if (it.code == 200) {
                        val data = it.data

                        val adapter = getAdapter()
                        val parentNode = adapter?.findParentNode(item)
                        adapter?.nodeRemoveData(adapter.data[parentNode!!],item)
                    }
                }onError {

                }
            }
            binding?.executePendingBindings()

        }
        @LoginCallback
        private fun huifu2(item: JokesItemCommentListEntity) {
          /*  if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
                gotoLogin()
            } else {*/
                BottomDialog.show(object :
                    OnBindView<BottomDialog>(R.layout.dialog_pinglun_write) {
                    override fun onBind(dialog: BottomDialog?, v: View?) {
                        val etPL = v?.findViewById<AppCompatEditText>(R.id.et_pl)
                        etPL?.postDelayed({ KeyboardUtils.open(etPL) }, 100)
                        etPL?.hint = "回复：" + item.commentUser.nickname
                        val imgSend = v?.findViewById<ImageView>(R.id.img_send)
                        etPL?.addTextChangedListener(object : TextWatcher {
                            override fun beforeTextChanged(
                                s: CharSequence?,
                                start: Int,
                                count: Int,
                                after: Int,
                            ) {
                            }

                            override fun onTextChanged(
                                s: CharSequence?,
                                start: Int,
                                before: Int,
                                count: Int,
                            ) {
                                imgSend?.isSelected = !s.isNullOrEmpty()
                            }

                            override fun afterTextChanged(s: Editable?) {

                            }
                        })

                        imgSend?.setOnClickListener {
                            if (!etPL?.text.toString().isNullOrEmpty()) {//提交评论
                                jokesViewModel.jokesCommentItem(fragment,
                                    item.commentItemId,
                                    etPL?.text.toString(),
                                    false) {
                                    if (it.code == 200) {
                                        val data = it.data

                                        val adapter = getAdapter()
                                        val parentNode = adapter?.findParentNode(item)
                                        adapter?.nodeAddData(adapter.data[parentNode!!], data)
                                        dialog?.dismiss()
                                    }

                                } onError {

                                }
                            }

                        }


                    }

                }).isAllowInterceptTouch = false
          //  }
        }

        override fun onClick(helper: BaseViewHolder, view: View, data: BaseNode, position: Int) {
            getAdapter()?.expandOrCollapse(position)
        }

        private fun gotoLogin() {
            val onBindView =
                object :
                    OnBindView<FullScreenDialog>(R.layout.layout_full_login, true) {
                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
                    override fun onBind(dialog: FullScreenDialog?, v: View?) {
                        val tvPhone = v?.findViewById<EditText>(R.id.edit_userName)
                        v?.findViewById<TextView>(R.id.tv_getCode)//获取验证码
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userLoginGetCode(
                                        fragment,
                                        tvPhone?.text.toString()
                                    ) {
                                        fragment.toast(it.msg)
                                    } onError {
                                        fragment.toast(it)

                                    }
                                } else {
                                    fragment.toast("请输入手机号码！")
                                }

                            }
                        v?.findViewById<TextView>(R.id.tv_loginByOwenPhone)
                            ?.setOnClickListener {
                                getOwnPhone(tvPhone)
                            }

                        val etPsd = v?.findViewById<TextView>(R.id.edit_password)

                        v?.findViewById<ImageView>(R.id.img_qq)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userPswReset(
                                        fragment,
                                        etPsd?.text.toString(), "111sam111",
                                        tvPhone?.text.toString()
                                    ) {
                                        fragment.toast(it.msg)
                                    } onError {
                                        fragment.toast(it)

                                    }
                                } else {
                                    fragment.toast("请输入手机号码！")
                                }
                            }
                        v?.findViewById<TextView>(R.id.btn_submit)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    if (!etPsd?.text.isNullOrEmpty()) {
                                        userViewModel.userLoginCode(
                                            fragment,
                                            etPsd?.text.toString(),
                                            tvPhone?.text.toString()
                                        ) {
                                            if (it.code === 200) {
                                                App.USER_TOKEN = it.data.token
                                                //存本地token
                                                ConfigTool.putString(Key.DataKey.TOKEN,
                                                    it.data.token)
                                                //登录成功
                                                EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))
                                                dialog?.dismiss()
                                            }
                                        } onError {
                                            fragment.toast(it)

                                        }
                                    } else {
                                        fragment.toast("请输入验证码！")

                                    }

                                } else {
                                    fragment.toast("请输入手机号码！")
                                }
                            }


                        val spannableStringBuilder = SpannableStringBuilder()
                        //设置文字
                        spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
                        //设置文字点击事件（用户协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "用户协议",

                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                        //设置文字点击事件（隐私协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "隐私协议",
                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        //设置颜色
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )


                        val tvXieYi = v?.findViewById<TextView>(R.id.tv_xieyi)
                        tvXieYi?.movementMethod = LinkMovementMethod.getInstance()
                        tvXieYi?.text = spannableStringBuilder

                    }

                }
            FullScreenDialog.show(onBindView).dialogLifecycleCallback = object :
                DialogLifecycleCallback<FullScreenDialog>() {
                override fun onDismiss(dialog: FullScreenDialog?) {
                    super.onDismiss(dialog)

                }

                override fun onShow(dialog: FullScreenDialog?) {
                    super.onShow(dialog)
                }

            }
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        fun getOwnPhone(phone: TextView?) {
            val phoneNumbers =
                fragment?.let { SIMCardInfo(it).phoneNumberS }
            if (phoneNumbers?.isNotEmpty() == true) {
                for (it in phoneNumbers) {

                }
                phone?.text = phoneNumbers[0]

            } else {
                fragment.toast("暂未获取到手机号")
            }


        }
    }
}